package com.example.firstdemo.ui.screens.pages.addProblem.addProblem.selectCarriage

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.firstdemo.network.api.addProblem.AddProblemApi
import com.example.firstdemo.network.api.addProblem.data.VehicleData
import com.example.firstdemo.network.service.NetworkException
import com.example.firstdemo.ui.screens.pages.addProblem.addProblem.selectCarriage.data.SelectCarriageUIState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class SelectCarriageViewModel : ViewModel() {
    private var _uiState = MutableStateFlow(SelectCarriageUIState())
    val uiState: StateFlow<SelectCarriageUIState> = _uiState

    var carriageList: List<VehicleData> = emptyList()
    fun getCarriageList() {
        viewModelScope.launch {
            try {
                carriageList = AddProblemApi.getCarriage().data ?: emptyList()
                _uiState.value = _uiState.value.copy(
                    carriageList = carriageList
                )
            } catch (_: NetworkException) {
            }
        }
    }

    fun filterCarriage(carriageNo: String) {
        _uiState.value = _uiState.value.copy(
            carriageList = carriageList.filter { it.carriage.carriageNo.contains(carriageNo) }
        )
    }
}